#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
群组数据访问对象
"""

from models.group import Group, db
from settings import get_logger

class GroupDAO:
    """
    群组数据访问对象
    负责群组数据的增删改查操作
    """
    
    def __init__(self):
        self.logger = get_logger(__name__)
    
    def get_groups_by_account(self, account):
        """
        根据账号获取所有群组
        
        Args:
            account: 微信账号
            
        Returns:
            list: 群组列表
        """
        try:
            groups = Group.query.filter_by(account=account).all()
            return groups
        except Exception as e:
            self.logger.error(f"根据账号获取群组失败: {e}")
            raise
            
    def get_groups_by_account_paginated(self, account, page=1, per_page=20, order_by=None):
        """
        根据账号获取群组（分页版本）
        
        Args:
            account: 微信账号
            page: 页码，从1开始
            per_page: 每页记录数
            order_by: 排序字段，格式为'字段名 asc'或'字段名 desc'
            
        Returns:
            Query: SQLAlchemy查询对象，可用于分页
        """
        try:
            query = Group.query.filter_by(account=account)
            return query
        except Exception as e:
            self.logger.error(f"根据账号获取群组（分页）失败: {e}")
            raise
    
    def get_group_by_id(self, group_id):
        """
        根据ID获取群组
        
        Args:
            group_id: 群组ID
            
        Returns:
            Group: 群组对象
        """
        try:
            group = Group.query.get(group_id)
            return group
        except Exception as e:
            self.logger.error(f"根据ID获取群组失败: {e}")
            raise
    
    def create_or_update_group(self, account, group_name, member_count, **kwargs):
        """
        创建或更新单个群组信息
        
        Args:
            account: 微信账号
            group_name: 群聊名称
            member_count: 群成员数量
            **kwargs: 其他群组属性
            
        Returns:
            Group: 创建或更新后的群组对象
        """
        try:
            # 查找是否已存在该群组
            group = Group.query.filter_by(account=account, group_name=group_name).first()
            
            if group:
                # 更新已存在的群组
                group.member_count = member_count
                
                # 更新其他属性
                for key, value in kwargs.items():
                    if hasattr(group, key):
                        setattr(group, key, value)
                
                db.session.commit()
                self.logger.info(f"更新群组成功: {group_name}")
            else:
                # 创建新群组
                group = Group(account=account, group_name=group_name, member_count=member_count)
                
                # 设置其他属性
                for key, value in kwargs.items():
                    if hasattr(group, key):
                        setattr(group, key, value)
                
                db.session.add(group)
                db.session.commit()
                self.logger.info(f"创建群组成功: {group_name}")
            
            return group
        except Exception as e:
            db.session.rollback()
            self.logger.error(f"创建或更新群组失败: {e}")
            raise
            
    def batch_create_or_update_groups(self, groups_data):
        """
        批量创建或更新群组信息
        
        Args:
            groups_data: 群组数据列表，每个元素为字典，包含account、group_name、member_count等字段
            
        Returns:
            tuple: (成功创建或更新的群组列表, 成功数量, 失败数量)
        """
        try:
            success_groups = []
            success_count = 0
            failed_count = 0
            
            # 获取所有群组名称，用于后续批量查询
            group_names = [group_data['group_name'] for group_data in groups_data]
            account = groups_data[0]['account'] if groups_data else None
            
            if not account or not group_names:
                return [], 0, 0
                
            # 批量查询已存在的群组
            existing_groups = Group.query.filter(
                Group.account == account,
                Group.group_name.in_(group_names)
            ).all()
            
            # 创建群组名称到群组对象的映射，便于快速查找
            existing_group_map = {group.group_name: group for group in existing_groups}
            
            # 批量处理所有群组数据
            for group_data in groups_data:
                try:
                    group_name = group_data.get('group_name')
                    member_count = group_data.get('member_count')
                    account = group_data.get('account')
                    
                    if not group_name or not account:
                        failed_count += 1
                        continue
                    
                    # 检查是否已存在该群组
                    if group_name in existing_group_map:
                        # 更新已存在的群组
                        group = existing_group_map[group_name]
                        group.member_count = member_count
                        
                        # 更新其他属性
                        for key, value in group_data.items():
                            if key not in ['group_name', 'account'] and hasattr(group, key):
                                setattr(group, key, value)
                    else:
                        # 创建新群组
                        group = Group(
                            account=account,
                            group_name=group_name,
                            member_count=member_count
                        )
                        
                        # 设置其他属性
                        for key, value in group_data.items():
                            if key not in ['group_name', 'account'] and hasattr(group, key):
                                setattr(group, key, value)
                        
                        db.session.add(group)
                    
                    success_groups.append(group)
                    success_count += 1
                    
                except Exception as e:
                    self.logger.error(f"批量处理群组时出错: {e}, 群组: {group_data}")
                    failed_count += 1
            
            # 一次性提交所有更改
            db.session.commit()
            self.logger.info(f"批量创建或更新群组成功，成功: {success_count}, 失败: {failed_count}")
            
            return success_groups, success_count, failed_count
            
        except Exception as e:
            db.session.rollback()
            self.logger.error(f"批量创建或更新群组失败: {e}")
            return [], 0, len(groups_data)
    
    def delete_group(self, group_id):
        """
        删除群组
        
        Args:
            group_id: 群组ID
            
        Returns:
            bool: 是否删除成功
        """
        try:
            group = Group.query.get(group_id)
            if group:
                db.session.delete(group)
                db.session.commit()
                self.logger.info(f"删除群组成功: ID={group_id}")
                return True
            return False
        except Exception as e:
            db.session.rollback()
            self.logger.error(f"删除群组失败: {e}")
            raise